package com.thread.laoma;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * 生产者消费者模式三（并发容器BlockingQueue）
 * Created by zhuangqi on 17-4-11.
 */
public class PcSyncDemo3 {
    static class MyBlockingQueue<E>{
        private int limit;
        private BlockingDeque<E> queue = null;
        public MyBlockingQueue(int limit) {
            this.limit = limit;
            this.queue = new LinkedBlockingDeque<>(limit);
        }
        private void put(E e) throws InterruptedException {
            queue.put(e);
        }

        private E take() throws InterruptedException {
            return queue.take();
        }
    }
    static class Product extends Thread{
        private MyBlockingQueue<String> myBlokingQueue;
        public Product(MyBlockingQueue<String> myBlokingQueue) {
            this.myBlokingQueue = myBlokingQueue;
        }
        @Override
        public void run() {
            int num = 0;
            while (true){
                try {
                    String task = String.valueOf(num);
                    myBlokingQueue.put(task);
                    num++;
                    System.out.println("生产："+num);
                    Thread.sleep((int) (Math.random() * 100));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    static class Consumer extends Thread{
        private MyBlockingQueue<String> myBlokingQueue;
        public Consumer(MyBlockingQueue<String> myBlokingQueue) {
            this.myBlokingQueue = myBlokingQueue;
        }
        @Override
        public void run() {
            while (true){
                try {
                    String data = myBlokingQueue.take();
                    System.out.println("消费："+ data);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        int sum = 10;
        MyBlockingQueue<String> queue = new MyBlockingQueue<>(sum);
        Thread thread = new Product(queue);
        Thread thread1 = new Consumer(queue);
        thread.start();
        thread1.start();
    }
}
